package uy.com.tsi2G7.superbet.ui;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.apache.shiro.SecurityUtils;

import uy.com.tsi2G7.superbet.bet.BetService;
import uy.com.tsi2G7.superbet.event.EventMarket;
import uy.com.tsi2G7.superbet.event.EventMarketResult;
import uy.com.tsi2G7.superbet.event.EventService;

@ManagedBean(name = "panelMenuBean")
@SessionScoped
public class PanelMenuBean {

    @ManagedProperty(value = "#{menuPopulator}")
    private MenuPopulator menuPopulator;
    private MenuDescriptor currentGroup;
    private MenuDescriptor currentElement;
    @EJB
	private EventService eventService;
    private static final String EVENT_TYPE_VIEW_PARAMETER = "eveT";
    private static final String EVENT_VIEW_PARAMETER = "eve";
    public static final String MARKET_VIEW_PARAMETER = "markId";
    public static final String MARKET_RESULT_VIEW_PARAMETER = "res";
    @EJB
    private BetService betService;
	private ArrayList<MarketDateEntry> marketEntries;
    
    public BetService getBetService() {
		return betService;
	}


	public void setBetService(BetService betService) {
		this.betService = betService;
	}

	@PostConstruct
    public void init() {
    }
	
	

    
    public static String getViewParameter(String name) {
        FacesContext fc = FacesContext.getCurrentInstance();
        String param = (String) fc.getExternalContext().getRequestParameterMap().get(name);
        if (param != null && param.trim().length() > 0) {
            return param;
        } else {
            return null;
        }
    }

   public MenuDescriptor getCurrentGroup() {
    	 String id = getViewParameter(EVENT_TYPE_VIEW_PARAMETER);
         if (currentGroup == null || !currentGroup.getId().equals(id)) {
             if (id != null) {
            	 currentGroup = findById(id,getGroups());
             }
             if (currentGroup == null) {
            	 currentGroup = getGroups().get(0);
             }
         }
         return currentGroup;
    }

	private MenuDescriptor findById(String id, List<MenuDescriptor> groups) {
		for (MenuDescriptor menuDescriptor : groups) {
			if(menuDescriptor.getId().longValue()==Long.valueOf(id).longValue())
				return menuDescriptor;
		}
		return null;
	}


	public MenuDescriptor getCurrentSample() {
		 String id = getViewParameter(EVENT_VIEW_PARAMETER);
	        if (currentElement == null || !currentElement.getId().equals(id)) {
	            if (id != null) {
	            	currentElement = findById(id,getCurrentGroup().getChildren());
	            }
	            if (currentElement == null) {
	            	currentElement = getCurrentGroup().getChildren().get(0);
	            }
	        }
	        return currentElement;
	}
    
    public List<MenuDescriptor> getGroups() {
		return menuPopulator.getGroupsList();
	}

	public MenuDescriptor findGroupById(String id) {
        for (MenuDescriptor menuDescriptor : getGroups()) {
			if(menuDescriptor.getId()==Long.valueOf(id))
				return menuDescriptor;
        } 
        return null;
    }

    public List<MarketDateEntry> getCurrentMarkets(){
    	SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    	Map<EventMarket, List<EventMarketResult>> markets = eventService.getCurrentMarkets(getCurrentSample().getId(),getCurrentGroup().getId());
    	 Map<String,List<MarketsDescriptor>> res=new HashMap<String, List<MarketsDescriptor>>();
		for (EventMarket market : markets.keySet()) {
			MarketsDescriptor mDesc = new MarketsDescriptor();
			mDesc.setId(market.getMarketId());
			mDesc.setName(market.getName());
			mDesc.setSource(market.getSource());
			mDesc.setStartDate(new SimpleDateFormat("dd/MM/yyyy HH:mm").format(market.getStartDate()));
			for (EventMarketResult result : markets.get(market)) {
				MarketsResultDescriptor markRes=new MarketsResultDescriptor();
				markRes.setAmount(new DecimalFormat("$ ###.##").format(result.getAmount().doubleValue()));
				markRes.setId(result.getId());
				markRes.setName(result.getName());
				markRes.setSource(result.getSource());
				mDesc.getChildren().add(markRes);
			}
			if(!res.containsKey(sdf.format(market.getStartDate())))
				res.put(sdf.format(market.getStartDate()), new ArrayList<MarketsDescriptor>());
			if((SecurityUtils.getSubject().isAuthenticated()&&SecurityUtils.getSubject().hasRole("administrador"))||(mDesc.getChildren()!=null&&mDesc.getChildren().size()!=0))
				res.get(sdf.format(market.getStartDate())).add(mDesc);
		}
		marketEntries=new ArrayList<MarketDateEntry>();
		for (String date : res.keySet()) {
			marketEntries.add(new MarketDateEntry(res.get(date),date));
		}
		return marketEntries;
	}
    
    
    

	public EventService getEventService() {
		return eventService;
	}

	public void setEventService(EventService eventService) {
		this.eventService = eventService;
	}


	public MarketsResultDescriptor getMarketResult() {
		return (MarketsResultDescriptor) getMarket().getChildById(getViewParameter(MARKET_RESULT_VIEW_PARAMETER));
		
		
	}
   
	public MarketsDescriptor getMarket(){
		String id = getViewParameter(MARKET_VIEW_PARAMETER);
		for (MarketDateEntry list : marketEntries) {
			for (MarketsDescriptor market : list.getValue()) {
				if(market.getId().longValue()==Long.valueOf(id).longValue())
					return market;
			}
		}
		return null;
	}


	public void refreshGroups() {
		menuPopulator.reset();
		
	}


	public MenuPopulator getMenuPopulator() {
		return menuPopulator;
	}


	public void setMenuPopulator(MenuPopulator menuPopulator) {
		this.menuPopulator = menuPopulator;
	}
   
}
